package com.example.easytraffic.core;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class DurationalTraffic implements Traffic {

	private volatile boolean isRunning;
	private long trafficDuration;
	private TimeUnit trafficDurationTimeUnit;
	private Traffic traffic;
	private Timer timer;
	
	public DurationalTraffic(Traffic traffic,
			long trafficDuration,
			TimeUnit trafficDurationTimeUnit) {
		this.isRunning = true;
		this.traffic = traffic;
		this.timer = new Timer();
		this.trafficDuration = trafficDuration;
		this.trafficDurationTimeUnit = trafficDurationTimeUnit;
	}

	public void run() {
		long durationInMillis = trafficDurationTimeUnit.toMillis(trafficDuration);
		timer.schedule(new TimerTask() {
			public void run() {
				stop();
			}
		}, durationInMillis);
		traffic.run();
	}
	
	public boolean isRunning() {
		return isRunning;
	}
	
	public void stop() {
		timer.cancel();
		traffic.stop();
		isRunning = false;
	}
}
